<?php

class FormController extends AweController {

    /**
     * @var string the default layout for the views.
     */
    public $layout = '//layouts/column2';
    public $admin = true;

    /**
     * Define filters for this Controllers
     * @return array Array of filters
     */
    public function filters() {
        return array(
            array('CrugeAccessControlFilter'),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Form;

//        $this->performAjaxValidation($model, 'form-form');

        if (isset($_POST['Form'])) {


            $model->attributes = $_POST['Form'];
            $model->welcome = $_POST['Form']['welcome'];
            $model->leave = $_POST['Form']['leave'];
            if ($model->welcome == 0) {
                $model->welcome_msg = '';
            }
            if ($model->leave == 0) {
                $model->leave_msg = '';
            }
            $this->performAjaxValidation($model, 'form-form');


            $form_structure = json_decode($model->form_structure, true);
            // Save Section
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if ($model->save()) {
                    foreach ($form_structure['sections'] as $section) {
                        $section_model = new Section;
                        $section_model->attributes = $section;
                        $section_model->form_id = $model->id;

                        if ($section_model->save()) {
                            foreach ($section['fields'] as $field) {
                                $field_model = new Field;
                                $field_model->attributes = $field;
                                $field_model->validations = json_encode($field_model->validations);
                                $field_model->section_id = $section_model->id;

                                if ($field_model->save()) {
                                    foreach ($field['fieldOptions'] as $option) {
                                        $option_model = new Option;
                                        $option_model->attributes = $option;
                                        $option_model->field_id = $field_model->id;
                                        if (!$option_model->save()) {
                                            throw new Exception("Error Saving Option");
                                        }
                                    }
                                } else {
                                    throw new Exception("Error Saving Field");
                                }
                            }
                        } else {
                            throw new Exception("Error Saving Section");
                        }
                    }
                } else {
                    throw new Exception("Error Saving Form");
                }

                $transaction->commit();
                Yii::app()->user->setFlash('success', Yii::t('noseyModule.app', 'Form saved successfully!'));
                $this->redirect(array('default/index'));
//                $this->redirect(array('update', 'id' => $model->id));
            } catch (Exception $e) {
                $transaction->rollBack();
//                // Pass data for ko model conversion
                $model->ko_data = json_encode($form_structure);
                Yii::app()->user->setFlash('error', Yii::t('noseyModule.app', 'There was an error saving the form.'));
            }
        }

        $this->render('create', array(
            'model' => $model,
            'fields' => json_encode(self::getCreatedFields()),
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        if ($model->welcome_msg != '') {
            $model->welcome = 1;
        }
        if ($model->leave_msg != '') {
            $model->leave = 1;
        }
        $this->performAjaxValidation($model, 'form-form');

        // Get data from database
        $form_structure['sections'] = $this->getFormatedKo($model);

        if (isset($_POST['Form'])) {
            $model->attributes = $_POST['Form'];
            $model->welcome = $_POST['Form']['welcome'];
            $model->leave = $_POST['Form']['leave'];
            $form_structure = json_decode($model->form_structure, true);

            // Save Section
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if ($model->save()) {
                    foreach ($form_structure['sections'] as $section) {
                        // Load section if already exists
                        if (isset($section['id']))
                            $section_model = Section::model()->findByPk($section['id']);
                        else
                            $section_model = new Section;
                        $section_model->attributes = $section;
                        $section_model->form_id = $model->id;

                        if ($section_model->save()) {
                            foreach ($section['fields'] as $field) {
                                // Load field if already exists
                                if (isset($field['id']))
                                    $field_model = Field::model()->findByPk($field['id']);
                                else
                                    $field_model = new Field;
                                $field_model->attributes = $field;
                                $field_model->validations = json_encode($field_model->validations);
                                $field_model->section_id = $section_model->id;

                                if ($field_model->save()) {
                                    foreach ($field['fieldOptions'] as $option) {
                                        // Load option if already exists
                                        if (isset($option['id']))
                                            $option_model = Option::model()->findByPk($option['id']);
                                        else
                                            $option_model = new Option;
                                        $option_model->attributes = $option;
                                        $option_model->field_id = $field_model->id;
                                        if (!$option_model->save()) {
                                            throw new Exception("Error Saving Option");
                                        }
                                    }
                                    // Delete options
                                    foreach ($field['deletedFieldOptions'] as $option) {
                                        $field_model = Option::model()->findByPk($option['id']);
                                        $field_model->delete();
                                    }
                                } else {
                                    throw new Exception(json_encode($field_model->errors));
                                }
                            }
                            // Delete fields
                            foreach ($section['deletedFields'] as $field) {
                                $field_model = Field::model()->findByPk($field['id']);
                                $field_model->delete();
                            }
                        } else {
                            throw new Exception("Error Saving Section");
                        }
                    }
                    // Delete sections
                    foreach ($form_structure['deletedSections'] as $section) {
                        $section_model = Section::model()->findByPk($section['id']);
                        $section_model->delete();
                    }
                } else {
                    throw new Exception("Error Saving Form");
                }

                $transaction->commit();
                Yii::app()->user->setFlash('success', Yii::t('noseyModule.app', 'Form saved successfully!'));
                $this->redirect(array('default/index'));
//                    $this->redirect(array('update', 'id' => $model->id));
            } catch (Exception $e) {
                $transaction->rollBack();
                Yii::app()->user->setFlash('error', Yii::t('noseyModule.app', 'There was an error saving the form.'));
            }
        }

        // Pass data for ko model conversion
        $model->ko_data = json_encode($form_structure);

        $this->render('update', array(
            'model' => $model,
            'fields' => json_encode(self::getCreatedFields()),
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('default/index'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionReport($id) {
        $model = $this->loadModel($id);

        $model->inicio = isset($_POST['inicio']) ? $_POST['inicio'] : date('d/m/Y', strtotime(date('Y-m-d') . '- 5 day'));
        $model->fin = isset($_POST['fin']) ? $_POST['fin'] : date('d/m/Y');

        $this->render('report', array(
            'model' => $model,
        ));
    }



    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Form::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Gives format to the from so it can be processed by the ko modelciew
     * @param FormModel $model
     * @return array formated model
     */
    protected function getFormatedKo($model) {
        $sections = array();
        foreach ($model->sections as $k => $section) {
            $sections[$k] = $section->attributes;
            $sections[$k]['fields'] = array();
            foreach ($section->fields as $j => $field) {
                $sections[$k]['fields'][$j] = $field->attributes;
                $sections[$k]['fields'][$j]['validations'] = json_decode($field->validations);
                $sections[$k]['fields'][$j]['availableWidgets'] = array();
                $sections[$k]['fields'][$j]['availableValidations'] = array();
                switch ($field->field_type) {
                    case Field::FIELD_TYPE_TEXT:
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_TEXT, 'text' => 'Textfield');
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_TEXTAREA, 'text' => 'Text Area');
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_NUMERICAL, 'text' => Yii::t('noseyModule.app', 'Numerical'));
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_DIGITS, 'text' => Yii::t('noseyModule.app', 'Digits'));
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_EMAIL, 'text' => Yii::t('noseyModule.app', 'Email'));
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_URL, 'text' => Yii::t('noseyModule.app', 'URL'));
                        break;
                    case Field::FIELD_TYPE_SIMPLE:
                        $sections[$k]['fields'][$j]['allowOptions'] = true;
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_RADIO, 'text' => 'Radio Buttons');
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                        break;
                    case Field::FIELD_TYPE_MULTIPLE:
                        $sections[$k]['fields'][$j]['allowOptions'] = true;
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_CHECKBOX, 'text' => 'Checkboxes');
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                        break;
                    case Field::FIELD_TYPE_DATE:
                    case Field::FIELD_TYPE_BOOLEAN:
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                        break;
                    case Field::FIELD_TYPE_RATING:
                        $sections[$k]['fields'][$j]['allowOptions'] = true;
                        $sections[$k]['fields'][$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_STAR_RATING, 'text' => 'Star Rating');
                        $sections[$k]['fields'][$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                        break;
                    default: break;
                }
                $sections[$k]['fields'][$j]['fieldOptions'] = array();
                foreach ($field->options as $option) {
                    $sections[$k]['fields'][$j]['fieldOptions'][] = $option->attributes;
                }
            }
        }

        return $sections;
    }

    protected function getCreatedFields() {
        $fields = array();

        foreach (Field::model()->findAll() as $j => $field) {
            $fields[$j] = $field->attributes;
            unset($fields[$j]['id']);
            unset($fields[$j]['weight']);
            $fields[$j]['validations'] = json_decode($field->validations);
            $fields[$j]['availableWidgets'] = array();
            $fields[$j]['availableValidations'] = array();
            switch ($field->field_type) {
                case Field::FIELD_TYPE_TEXT:
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_TEXT, 'text' => 'Textfield');
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_TEXTAREA, 'text' => 'Text Area');
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_NUMERICAL, 'text' => Yii::t('noseyModule.app', 'Numerical'));
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_DIGITS, 'text' => Yii::t('noseyModule.app', 'Digits'));
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_EMAIL, 'text' => Yii::t('noseyModule.app', 'Email'));
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_URL, 'text' => Yii::t('noseyModule.app', 'URL'));
                    break;
                case Field::FIELD_TYPE_SIMPLE:
                    $fields[$j]['allowOptions'] = true;
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_RADIO, 'text' => 'Radio Buttons');
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                    break;
                case Field::FIELD_TYPE_MULTIPLE:
                    $fields[$j]['allowOptions'] = true;
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_CHECKBOX, 'text' => 'Checkboxes');
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                    break;
                case Field::FIELD_TYPE_DATE:
                case Field::FIELD_TYPE_BOOLEAN:
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                    break;
                case Field::FIELD_TYPE_RATING:
                    $fields[$j]['allowOptions'] = true;
                    $fields[$j]['availableValidations'][] = array('value' => Field::VALIDATION_TYPE_REQUIRED, 'text' => Yii::t('noseyModule.app', 'Required'));
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_STAR_RATING, 'text' => 'Star Rrating');
                    $fields[$j]['availableWidgets'][] = array('value' => Field::WIDGET_TYPE_SELECT, 'text' => 'Dropdown');
                    break;

                default: break;
            }
            $fields[$j]['fieldOptions'] = array();
            foreach ($field->options as $k => $option) {
                $fields[$j]['fieldOptions'][$k] = $option->attributes;
                unset($fields[$j]['fieldOptions'][$k]['id']);
            }
        }

        return $fields;
    }

}
